import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'

export const API = '/api';

const instance = axios.create({
    // baseURL: '/meetingFront',
    // baseURL: 'https://api.huihaometa.com/',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    // withCredentials: true
})

// 拦截器 - 请求拦截
instance.interceptors.request.use((config: AxiosRequestConfig) => {
    // 部分接口需要拿到Token
    // let token = localStorage.getItem('token')
    // if (token) {
    //     config.headers!.authorization = token;
    // }
    config.data = config.data
    return config
}, err => {
    return Promise.reject(err)
})

// 拦截器 - 响应拦截
instance.interceptors.response.use(
    // 因为我们接口的数据都在res.data下，所以我们直接返回res.data
    (res: AxiosResponse) => {
        const dts = res?.data;
        if (dts.code !== 200) {
            return Promise.reject(dts)
        }
        return dts;
    },
    (err: any) => Promise.reject(err),
)


export function get(url: string, params?: {}) {
    return new Promise((resolve, reject) => {
        instance.get(url, {
            params: params
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err.data)
        })
    });
}


export function post(url: string, data: {}) {
    return new Promise((resolve, reject) => {
        instance.post(url, data)
            .then((res: any) => {
                resolve(res);
            })
            .catch(err => {
                reject(err)
            })
    });
}

export function upload(url: string, file: any) {
    return new Promise((resolve, reject) => {
        instance.post(url, file, {
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then((res: any) => {
            resolve(res.data);
        })
            .catch(err => {
                reject(err)
            })
    });
}